package com.hncc.kumao.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hncc.kumao.biz.IBreakpointUploadTaskBiz;
import com.hncc.kumao.biz.INetdiskAccessTokenBiz;
import com.hncc.kumao.entity.BreakpointUploadTask;
import com.hncc.kumao.entity.BreakpointUploadTaskInfo;
import com.hncc.kumao.entity.NetdiskAccessToken;
import com.hncc.kumao.exception.KumaoException;
import com.hncc.kumao.tool.CheckNetdiskTokenTool;
import com.hncc.kumao.tool.SMBOperation;
import com.hncc.kumao.tool.UploadFileTool;
import com.hncc.kumao.util.BreakpointUploadUtils;
import com.hncc.kumao.util.ConstValue;
import com.hncc.kumao.util.MyFileUtils;

/**
 * 断点上传Action
 * @author chen
 */
public class BreakpointUploadTaskAction extends BaseAction {

    private IBreakpointUploadTaskBiz breakpointUploadTaskBiz;
    private INetdiskAccessTokenBiz netdiskAccessTokenBiz;
    private UploadFileTool uploadFileTool;
    private static ExecutorService executor = Executors.newFixedThreadPool(5);
    
    //添加断点上传任务
    public void add() {
        try {
            //获取请求数据
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            JSONObject jsonObject = JSON.parseObject(requestData);
            //解析出网盘令牌对象
            NetdiskAccessToken netdiskAccessToken = jsonObject.getObject("netdiskToken", NetdiskAccessToken.class);
            //解析出离线下载对象
            BreakpointUploadTask breakpointUploadTask = jsonObject.getObject("taskInfo", BreakpointUploadTask.class);
            //System.out.println("任务信息: " + breakpointUploadTask);
            try {
                //校验网盘令牌
                checkNetdiskAccessToken(netdiskAccessToken);
                //校验任务信息
                checkBreakpointUploadTask(breakpointUploadTask);
                //单独校验SMB网盘信息的有效性
                if(netdiskAccessToken.getNetdiskType() == ConstValue.NETDISK_TYPE_SMB) {
                    if(!SMBOperation.check(netdiskAccessToken, breakpointUploadTask.getFileUri())) {
                        throw new KumaoException("网盘信息无效，无法访问到目标网盘");
                    }                    
                }
            } catch (KumaoException e) {
                e.printStackTrace();
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, e.getMessage());
                return;
            }
            
            netdiskAccessToken.setUserId(userId);
            String netdiskId = netdiskAccessTokenBiz.add(netdiskAccessToken);
            
            breakpointUploadTask.setUserId(userId);
            //TODO 测试外键
            //breakpointUploadTask.setTargetNetdiskAccessTokenId(netdiskId);
            breakpointUploadTask.setNetdiskAccessToken(netdiskAccessToken);
            breakpointUploadTask.setState(ConstValue.BU_TASK_STATE_CREATE);
            breakpointUploadTask.setCreateTime(new Date());
            if(breakpointUploadTask.getFileInfo() != null) {
                breakpointUploadTask.setFileInfoString(JSON.toJSONString(breakpointUploadTask.getFileInfo()));
            }
            String taskId = breakpointUploadTaskBiz.add(breakpointUploadTask);
            
            //将离线下载任务信息存入Redis
            BreakpointUploadTaskInfo taskInfo = BreakpointUploadUtils.getBreakpointUploadTaskInfo(taskId);
            taskInfo.setTaskId(taskId);
            taskInfo.setTotalFragmentNumber(breakpointUploadTask.getTotalFragmentNumber());
            taskInfo.setCreateTime(breakpointUploadTask.getCreateTime());
            taskInfo.setState(breakpointUploadTask.getState());
            BreakpointUploadUtils.setBreakpointUploadTaskInfo(taskInfo);
            
            //将离线任务id返回
            jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, taskId);
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
        }
    }
    
    private File fileFragment;//分片文件数据
    private String fileFragmentFileName;
    private String fileFragmentContentType;
    
    //上传文件分片
    public void upload() {
        try {
            HttpServletRequest request = getRequest();
            String token = request.getParameter("token");
            final String taskId = request.getParameter("taskId");
            String currentFragmentNumberString = request.getParameter("currentFragmentNumber");
            String userId = "";
            BreakpointUploadTask breakpointUploadTask = null;
            Integer currentFragmentNumber = null;
            try {
                //手动校验令牌
                userId = checkToken(token);
                //校验任务id
                breakpointUploadTask = checkTaskId(taskId, userId);
                //System.out.println("任务信息: " + breakpointUploadTask);
                switch (breakpointUploadTask.getState()) {
                case ConstValue.BU_TASK_STATE_CANCEL:
                case ConstValue.BU_TASK_STATE_DELETE:
                case ConstValue.BU_TASK_STATE_GET_File_SUCCESS:
                case ConstValue.BU_TASK_STATE_UPLOAD_FILE:
                case ConstValue.BU_TASK_STATE_UPLOAD_SUCCESS:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已不能再接收文件分片");
                    return;
                }
                //校验当前片段编号
                currentFragmentNumber = checkFragmentNumber(currentFragmentNumberString);
            } catch (KumaoException e) {
                e.printStackTrace();
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, e.getMessage());
                return;
            }
            if(fileFragment == null) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "序号为" + currentFragmentNumber + "的文件分片接收失败");
                return;
            }
            
            //从redis中获取任务信息
            BreakpointUploadTaskInfo taskInfo = BreakpointUploadUtils.getBreakpointUploadTaskInfo(taskId);
            //改变状态
            if(breakpointUploadTask.getState() != ConstValue.BU_TASK_STATE_GET_File) {
                //第一次接收文件分片
                if(BreakpointUploadUtils.getSuccessFragmentNumber(taskId) <= 0) {
                    updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_GET_File, 
                            new Date(), ConstValue.BU_TASK_DATE_START_GET_TIME);
                } else {
                    updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_GET_File, null, -1);
                }
            }
            
            BreakpointUploadUtils.addCurrentFragment(taskId, currentFragmentNumber);
            
            //将文件片段保存到本地
            String saveFileDir = "/" + ConstValue.UPLOAD_DIR_NAME + "/" + breakpointUploadTask.getUserId() + 
                    "/" + breakpointUploadTask.getId();
            String fileFragmentName = currentFragmentNumber + ".fragment";
            String fileFragmentSavePath = ConstValue.BASE_RES_PATH + saveFileDir + "/" + fileFragmentName;
            File destFile = new File(fileFragmentSavePath);
            FileUtils.copyFile(fileFragment, destFile);
            
            //当前分片保存完成，进行相应的更新
            BreakpointUploadUtils.removeCurrentFragment(taskId, currentFragmentNumber);
            BreakpointUploadUtils.addSuccessFragment(taskId, currentFragmentNumber);
            taskInfo.setSuccessFragmentNumber(BreakpointUploadUtils.getSuccessFragmentNumber(taskId));
            //更新任务信息
            BreakpointUploadUtils.setBreakpointUploadTaskInfo(taskInfo);
            //判断一下是否所有分片都上传完成
            if(breakpointUploadTask.getTotalFragmentNumber() == BreakpointUploadUtils.getSuccessFragmentNumber(taskId)) {
                //所有分片上传完成
                
                //更新信息
                updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_GET_File_SUCCESS,
                        new Date(), ConstValue.BU_TASK_DATE_END_GET_TIME);
                
                //检查接收成功的文件序号是否连贯
                boolean coherent = BreakpointUploadUtils.getSuccessFragmentNumberIsCoherent(taskId);
                if(!coherent) {
                    //接收文件失败
                    
                    //删除所有文件分片
                    File deleteFile = new File(ConstValue.BASE_RES_PATH + saveFileDir);
                    try {
                        MyFileUtils.deleteFile(deleteFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    
                    //删除存储的分片信息
                    BreakpointUploadUtils.removeAllCurrentFragment(taskId);
                    BreakpointUploadUtils.removeAllSuccessFragment(taskId);
                    taskInfo.setSuccessFragmentNumber(BreakpointUploadUtils.getSuccessFragmentNumber(taskId));
                    //更新信息
                    updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_GET_File_FAIL, null, -1);
                    
                    //返回错误信息
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "文件分片接收失败，接收的分片数量达到分片总数，但是分片顺序不连贯，请重新上传所有分片");
                    return;
                }
                
                //拼接文件
                //从传过来的uri中获取文件名
                String saveFileName = new File(breakpointUploadTask.getFileUri()).getName();
                //拼接路径
                String saveFilePath = ConstValue.BASE_RES_PATH + saveFileDir + "/" + saveFileName;
                //判断该文件路径是否存在，如果不存在，则创建出路径
                File saveFile = new File(saveFilePath);
                if(!saveFile.exists()) {
                    if(!saveFile.getParentFile().exists()) {
                        saveFile.getParentFile().mkdirs();
                    }
                }
                //获取所有完成的序号数组(排序后的)
                Integer[] array = BreakpointUploadUtils.getSuccesssFragmentSortArray(taskId);
                //进行拼接操作(边拼边删)
                FileOutputStream fos = new FileOutputStream(saveFile);
                int len;
                byte[] buff = new byte[1024];
                for(int i = 0; i < array.length; i++) {
                    File fragmengFile = new File(ConstValue.BASE_RES_PATH + saveFileDir + "/" + array[i] + ".fragment");
                    FileInputStream fis = new FileInputStream(fragmengFile);
                    while((len = fis.read(buff)) != -1) {
                        fos.write(buff, 0, len);
                    }
                    fis.close();
                    fragmengFile.delete();
                }
                fos.close();
                //获取文件大小和md5进行校验
                long saveFileSize = saveFile.length();
                FileInputStream tempFis = new FileInputStream(saveFile);
                String saveFileMD5 = DigestUtils.md5Hex(tempFis);
                tempFis.close();
                if((saveFileSize + "").equals(breakpointUploadTask.getFileSize()) 
                        && saveFileMD5.equals(breakpointUploadTask.getFileMd5())) {
                    //文件拼接没问题
                    
                    //更新信息
                    BreakpointUploadUtils.removeAllCurrentFragment(taskId);
                    BreakpointUploadUtils.removeAllSuccessFragment(taskId);
                    breakpointUploadTask.setFileServerPath(saveFile.getAbsolutePath());//设置路径
                    updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_UPLOAD_FILE,
                            new Date(), ConstValue.BU_TASK_DATE_START_UPLOAD_TIME);
                    
                    //返回信息
                    jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, "文件分片上传完成");
                    
                    executor.submit(new Runnable() {
                        @Override
                        public void run() {
                            //获取网盘信息
                            BreakpointUploadTask breakpointUploadTask = breakpointUploadTaskBiz.get(taskId);
                            BreakpointUploadTaskInfo taskInfo = BreakpointUploadUtils.getBreakpointUploadTaskInfo(taskId);
                            //TODO 测试外键
                            //NetdiskAccessToken netdiskAccessToken = netdiskAccessTokenBiz.get(breakpointUploadTask.getTargetNetdiskAccessTokenId());
                            NetdiskAccessToken netdiskAccessToken = breakpointUploadTask.getNetdiskAccessToken();
                            try {
                                //调用工具类上传进行上传
                                uploadFileTool.uploadFile(breakpointUploadTask, netdiskAccessToken);
                                //上传文件成功
                                System.out.println("上传文件成功");
                                //更新信息
                                updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_UPLOAD_SUCCESS,
                                        new Date(), ConstValue.BU_TASK_DATE_END_UPLOAD_TIME);
                                //返回信息
                                //jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, "文件已上传至目标网盘");
                                //return;
                            } catch (KumaoException e) {
                                e.printStackTrace();
                                //上传文件失败
                                System.out.println("上传文件失败");
                                //更新信息
                                updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_UPLOAD_FAIL,
                                        new Date(), ConstValue.BU_TASK_DATE_END_UPLOAD_TIME);
                                //返回信息
                                //jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, e.getMessage());
                                //return;
                            } catch (Exception e) {
                                e.printStackTrace();
                                //上传文件失败
                                System.out.println("上传文件失败");
                                //更新信息
                                updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_UPLOAD_FAIL,
                                        new Date(), ConstValue.BU_TASK_DATE_END_UPLOAD_TIME);
                                //返回信息
                                //jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "文件上传至目标网盘失败");
                                //return;
                            }
                        }
                    });
                } else {
                    //文件拼接有问题
                    
                    //删除所有文件分片
                    File deleteFile = new File(ConstValue.BASE_RES_PATH + saveFileDir);
                    try {
                        MyFileUtils.deleteFile(deleteFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    
                    //删除存储的所有文件
                    BreakpointUploadUtils.removeAllCurrentFragment(taskId);
                    BreakpointUploadUtils.removeAllSuccessFragment(taskId);
                    taskInfo.setSuccessFragmentNumber(BreakpointUploadUtils.getSuccessFragmentNumber(taskId));
                    //更新信息
                    updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_GET_File_FAIL, null, -1);
                    
                    //返回错误信息
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "文件拼接结果有误，请检查上传的文件大小和文件MD5还有文件分片上传的序号排列是否有误，然后重新上传所有分片");
                    return;
                }
            } else {
                jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, currentFragmentNumber);
            }
        } catch (KumaoException e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, e.getMessage());
            e.printStackTrace();
            return;
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
            return;
        }
    }
    
    //获取断点上传信息
    public void info() {
        try {
            //获取请求数据
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            String taskId = JSON.parseObject(requestData).getString("taskId");
            
            BreakpointUploadTask breakpointUploadTask;
            //校验任务id
            try {
                breakpointUploadTask = checkTaskId(taskId, userId);
            } catch (Exception e) {
                e.printStackTrace();
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, e.getMessage());
                return;
            }
            
            switch (breakpointUploadTask.getState()) {
            case ConstValue.BU_TASK_STATE_CREATE:
            case ConstValue.BU_TASK_STATE_GET_File:
            case ConstValue.BU_TASK_STATE_PAUSE_GET_File:
            case ConstValue.BU_TASK_STATE_GET_File_SUCCESS:
            case ConstValue.BU_TASK_STATE_GET_File_FAIL:
            case ConstValue.BU_TASK_STATE_UPLOAD_FILE:
            case ConstValue.BU_TASK_STATE_UPLOAD_SUCCESS:
            case ConstValue.BU_TASK_STATE_UPLOAD_FAIL:
            case ConstValue.BU_TASK_STATE_CANCEL:
                BreakpointUploadTaskInfo taskInfo = BreakpointUploadUtils.getBreakpointUploadTaskInfo(taskId);
                jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, taskInfo);
                return;
            case ConstValue.BU_TASK_STATE_DELETE:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已删除");
                return;
            default:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "暂无任务信息");
                return;
            }
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
        }
    }
    
    //暂停断点上传任务
    public void pause() {
        try {
            //获取请求数据
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            String taskId = JSON.parseObject(requestData).getString("taskId");
            
            BreakpointUploadTask breakpointUploadTask;
            //校验任务id
            try {
                breakpointUploadTask = checkTaskId(taskId, userId);
            } catch (Exception e) {
                e.printStackTrace();
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, e.getMessage());
                return;
            }
            
            //获取任务信息
            BreakpointUploadTaskInfo taskInfo = BreakpointUploadUtils.getBreakpointUploadTaskInfo(taskId);
            
            switch (breakpointUploadTask.getState()) {
            case ConstValue.BU_TASK_STATE_CREATE:
            case ConstValue.BU_TASK_STATE_GET_File:
            case ConstValue.BU_TASK_STATE_PAUSE_GET_File:
                //更改状态
                updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_PAUSE_GET_File, null, -1);
                Integer fragmentNumber = BreakpointUploadUtils.getSuccessFragmentNumberMaxCoherent(taskId);
                jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, fragmentNumber);
                return;
            case ConstValue.BU_TASK_STATE_GET_File_SUCCESS:
            case ConstValue.BU_TASK_STATE_UPLOAD_SUCCESS:
            case ConstValue.BU_TASK_STATE_UPLOAD_FILE:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已接收分片结束，已不能暂停");
                return;
            case ConstValue.BU_TASK_STATE_GET_File_FAIL:
            case ConstValue.BU_TASK_STATE_UPLOAD_FAIL:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已失败，需要重新上传所有分片");
                return;
            case ConstValue.BU_TASK_STATE_CANCEL:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已取消");
                return;
            case ConstValue.BU_TASK_STATE_DELETE:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已删除");
                return;
            }
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
        }
    } 
    
    //取消断点上传任务
    public void cancel() {
        try {
            //获取请求数据
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            String taskId = JSON.parseObject(requestData).getString("taskId");
            
            BreakpointUploadTask breakpointUploadTask;
            //校验任务id
            try {
                breakpointUploadTask = checkTaskId(taskId, userId);
            } catch (Exception e) {
                e.printStackTrace();
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, e.getMessage());
                return;
            }
            
            //删除所有文件
            File deleteFile = new File(ConstValue.BASE_RES_PATH + "/breakupload/" + 
            breakpointUploadTask.getUserId() + "/" + breakpointUploadTask.getId());
            try {
                MyFileUtils.deleteFile(deleteFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            //删除存储的分片信息
            BreakpointUploadUtils.removeAllCurrentFragment(taskId);
            BreakpointUploadUtils.removeAllSuccessFragment(taskId);
            //获取任务信息
            BreakpointUploadTaskInfo taskInfo = BreakpointUploadUtils.getBreakpointUploadTaskInfo(taskId);
            //更改状态
            updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_DELETE, null, -1);
            //删除任务信息
            BreakpointUploadUtils.removeBreakpointUploadTaskInfo(taskId);
            jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, "删除成功");
            return;
            
            /*//获取任务信息
            BreakpointUploadTaskInfo taskInfo = BreakpointUploadUtils.getBreakpointUploadTaskInfo(taskId);
            switch (breakpointUploadTask.getState()) {
            case ConstValue.BU_TASK_STATE_CREATE:
            case ConstValue.BU_TASK_STATE_GET_File:
            case ConstValue.BU_TASK_STATE_PAUSE_GET_File:
            case ConstValue.BU_TASK_STATE_CANCEL:
                
                //删除所有文件分片
                File deleteFile = new File(ConstValue.BASE_RES_PATH + "/breakupload/" + 
                breakpointUploadTask.getUserId() + "/" + breakpointUploadTask.getId());
                try {
                    MyFileUtils.deleteFile(deleteFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
                //删除存储的分片信息
                BreakpointUploadUtils.removeAllCurrentFragment(taskId);
                BreakpointUploadUtils.removeAllSuccessFragment(taskId);
                taskInfo.setSuccessFragmentNumber(BreakpointUploadUtils.getSuccessFragmentNumber(taskId));
                //更改状态
                updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_CANCEL, null, -1);
                //删除任务信息
                BreakpointUploadUtils.removeBreakpointUploadTaskInfo(taskId);
                jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, "取消成功");
                return;
            case ConstValue.BU_TASK_STATE_GET_File_SUCCESS:
            case ConstValue.BU_TASK_STATE_UPLOAD_SUCCESS:
            case ConstValue.BU_TASK_STATE_UPLOAD_FILE:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已接收分片结束，已不能取消");
                return;
            case ConstValue.BU_TASK_STATE_GET_File_FAIL:
            case ConstValue.BU_TASK_STATE_UPLOAD_FAIL:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务接收分片失败，已不能取消");
                return;
            case ConstValue.BU_TASK_STATE_DELETE:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已删除");
                return;
            }*/
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
        }
    }
    
    //删除断点上传任务
    public void delete() {
        try {
            //获取请求数据
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            String taskId = JSON.parseObject(requestData).getString("taskId");
            
            BreakpointUploadTask breakpointUploadTask;
            //校验任务id
            try {
                breakpointUploadTask = checkTaskId(taskId, userId);
            } catch (Exception e) {
                e.printStackTrace();
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, e.getMessage());
                return;
            }
            
            //删除所有文件
            File deleteFile = new File(ConstValue.BASE_RES_PATH + "/breakupload/" + 
            breakpointUploadTask.getUserId() + "/" + breakpointUploadTask.getId());
            try {
                MyFileUtils.deleteFile(deleteFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            //删除存储的分片信息
            BreakpointUploadUtils.removeAllCurrentFragment(taskId);
            BreakpointUploadUtils.removeAllSuccessFragment(taskId);
            //获取任务信息
            BreakpointUploadTaskInfo taskInfo = BreakpointUploadUtils.getBreakpointUploadTaskInfo(taskId);
            //更改状态
            updateTaskInfo(breakpointUploadTask, taskInfo, ConstValue.BU_TASK_STATE_DELETE, null, -1);
            //删除任务信息
            BreakpointUploadUtils.removeBreakpointUploadTaskInfo(taskId);
            jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, "删除成功");
            return;
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
        }
    }
    
    //更新任务信息
    private void updateTaskInfo(BreakpointUploadTask breakpointUploadTask, BreakpointUploadTaskInfo taskInfo, 
            Integer state, Date timeInfo, Integer dateType) {
        //设置状态
        breakpointUploadTask.setState(state);
        taskInfo.setState(state);
        //设置时间
        switch (dateType) {
        case ConstValue.BU_TASK_DATE_CREATE_TIME://创建
            breakpointUploadTask.setCreateTime(timeInfo);
            taskInfo.setCreateTime(timeInfo);
            break;
        case ConstValue.BU_TASK_DATE_START_GET_TIME://开始接收分片
            breakpointUploadTask.setStartGetTime(timeInfo);
            taskInfo.setStartGetTime(timeInfo);
            break;
        case ConstValue.BU_TASK_DATE_END_GET_TIME://结束接收分片
            breakpointUploadTask.setEndGetTime(timeInfo);
            taskInfo.setEndGetTime(timeInfo);
            break;
        case ConstValue.BU_TASK_DATE_START_UPLOAD_TIME://开始向网盘上传
            breakpointUploadTask.setStartUploadTime(timeInfo);
            taskInfo.setStartUploadTime(timeInfo);
            break;
        case ConstValue.BU_TASK_DATE_END_UPLOAD_TIME://结束向网盘上传
            breakpointUploadTask.setEndUploadTime(timeInfo);
            taskInfo.setEndUploadTime(timeInfo);
            break;
        }
        //进行更新
        breakpointUploadTaskBiz.update(breakpointUploadTask);
        BreakpointUploadUtils.setBreakpointUploadTaskInfo(taskInfo);
    }
    
    //校验网盘对象
    private void checkNetdiskAccessToken(NetdiskAccessToken netdiskAccessToken) {
        if(netdiskAccessToken == null) {
            throw new KumaoException("缺少网盘令牌信息");
        }
        if(netdiskAccessToken.getNetdiskType() == null) {
            throw new KumaoException("网盘类型不能为空");
        }
        if(netdiskAccessToken.getNetdiskUrl() == null || netdiskAccessToken.getNetdiskUrl().trim().length() <= 0) {
            if(netdiskAccessToken.getNetdiskType() != ConstValue.NETDISK_TYPE_BAIDU && 
                    netdiskAccessToken.getNetdiskType() != ConstValue.NETDISK_TYPE_JIANGUOYUN) {
                throw new KumaoException("网盘URL不能为空");
            }
        }
        if((netdiskAccessToken.getAccessToken() == null || netdiskAccessToken.getAccessToken().trim().length() <= 0)
                && (netdiskAccessToken.getUsername() == null || netdiskAccessToken.getUsername().trim().length() <= 0
                        || netdiskAccessToken.getPassword() == null || netdiskAccessToken.getPassword().trim().length() <= 0)
                && netdiskAccessToken.getTokenType() != ConstValue.TOKEN_TYPE_ANONYMITY) {
            throw new KumaoException("缺少访问网盘必要信息，请检查网盘令牌或用户名和密码");
        }
        if(!CheckNetdiskTokenTool.checkNetdiskToken(netdiskAccessToken)) {
            throw new KumaoException("网盘信息无效，无法访问到目标网盘");
        }
    }
    
    //校验任务信息
    private void checkBreakpointUploadTask(BreakpointUploadTask breakpointUploadTask) {
        if(breakpointUploadTask.getFileSize() == null || breakpointUploadTask.getFileSize().trim().length() <= 0) {
            throw new KumaoException("文件大小不能为空");
        }
        if(breakpointUploadTask.getFileMd5() == null || breakpointUploadTask.getFileMd5().trim().length() <= 0) {
            throw new KumaoException("文件MD5不能为空");
        }
        if(breakpointUploadTask.getTotalFragmentNumber() == null) {
            throw new KumaoException("文件总分片数不能为空");
        }
        if(breakpointUploadTask.getFileUri() == null || breakpointUploadTask.getFileUri().trim().length() <= 0) {
            throw new KumaoException("文件在网盘存储的路径不能为空");
        }
    }
    
    //校验任务id
    private BreakpointUploadTask checkTaskId(String taskId, String userId) {
        if(taskId == null || taskId.trim().length() <= 0) {
            throw new KumaoException("任务id不能为空");
        }
        //根据任务id查询数据库
        BreakpointUploadTask breakpointUploadTask = breakpointUploadTaskBiz.get(taskId);
        if(breakpointUploadTask == null) {
            throw new KumaoException("任务id有误");
        }
        if(!breakpointUploadTask.getUserId().equals(userId)) {
            throw new KumaoException("任务id与令牌信息不匹配");
        }
        return breakpointUploadTask;
    }
    
    //校验当前分片序号
    private Integer checkFragmentNumber(String currentFragmentNumberString) {
        if(currentFragmentNumberString == null || currentFragmentNumberString.trim().length() <= 0) {
            throw new KumaoException("当前分片序号不能为空");
        }
        Integer currentFragmentNumber;
        try {
            currentFragmentNumber = Integer.parseInt(currentFragmentNumberString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new KumaoException("当前分片序号数值有误");
        }
        return currentFragmentNumber;
    }
    
    
    public void setBreakpointUploadTaskBiz(IBreakpointUploadTaskBiz breakpointUploadTaskBiz) {
        this.breakpointUploadTaskBiz = breakpointUploadTaskBiz;
    }
    public void setNetdiskAccessTokenBiz(INetdiskAccessTokenBiz netdiskAccessTokenBiz) {
        this.netdiskAccessTokenBiz = netdiskAccessTokenBiz;
    }
    public void setUploadFileTool(UploadFileTool uploadFileTool) {
        this.uploadFileTool = uploadFileTool;
    }

    public void setFileFragment(File fileFragment) {
        this.fileFragment = fileFragment;
    }
    public void setFileFragmentFileName(String fileFragmentFileName) {
        this.fileFragmentFileName = fileFragmentFileName;
    }
    public void setFileFragmentContentType(String fileFragmentContentType) {
        this.fileFragmentContentType = fileFragmentContentType;
    }
    
}
